const app = getApp()
import debounce from "../../utils/debounce"
import api from '../../utils/api'
import {
  isPointInPolygon,countCircle,numberToRadius,numberToDegree
} from '../../utils/isPointInPolygon.js';

// 引入SDK核心类，js文件根据自己业务，位置可自行放置
var QQMapWX = require('../../libs/qqmap-wx-jssdk');
var tencentMap;



Page({
  data: {
    flag:false,
 curLatitude:39.907564,
curLongitude:116.172309,

    markersArr: [],
    addressList:[],
    markers: [],
    polygons: [],
    paramspolygones: [],
    latitude: 39.90555,
    longitude: 116.22289,
    accuracy: 65, //位置的精度  113.6653,34.752465
    scale: 16, //缩放级别
    province: '', //省份
    city: '', //城市
    district: '', //区
    street : '' , //街道
    address:'河南省郑州市二七区正兴街', //地址
    name:'', //店名
    lonValue :'', //输入的经度
    latValue :'' , //输入的纬度
    searchValue: '', //搜索框输入值
    searchIndex: 0, //快捷搜索选中的默认值
    searchingtext:'请输入您想要上门的地址',
    siteData:[],//地址列表

  },
//定位点是否在围栏内
  tapHandle:function() {
    if (!this.data.polygons.length) {
      return wx.showToast({
        title: '当前没有设置围栏',
        icon: 'none',
        mask: true
      })
    }
    //遍历多个电子围栏
    for(var i=0; i < this.data.polygons.length; i++){
        var array = this.data.polygons[i].points;
        var indexId = this.data.polygons[i].id;
        var newArray = [];
        //遍历电子围栏内坐标点
        for (var j = 0; j < array.length; j++) {
            var obj = {};
            obj.lng = array[j].longitude;
            obj.lat = array[j].latitude;
            newArray.push(obj)
        }
        this.setData({
            paramspolygones: newArray
        })
        let nowPoint = {};
        nowPoint.lat = this.data.latitude;
        nowPoint.lng = this.data.longitude;
        //true表示在围栏内反之围栏外
        let flag = isPointInPolygon(nowPoint, newArray);
       
       if(flag){
           this.data.flag =flag;
           this.setData({
               id: indexId
           })
       }
    }
      wx.showToast({
          title: this.data.flag ? '在回收服务区域内 : 可下单':'不在回收服务区域内 : 暂不可下单',
          icon: 'none'
      })
  },
    //获取当前采样点经纬度事件
  tapM:function() {
    //this.getLocation() //获取当前采样点经纬度事件
    var that = this
    wx.getLocation({
      type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success: function (res) {
        //赋值经纬度
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,

        })
      }
    })
    console.log('点击有效')
    //this.mapCtx.moveToLocation() //地图回到当前位置


      that.mapCtx.moveToLocation();

      console.log(that.mapCtx)


},

// 获取区域
    getPolygons() {
    api._get('electricFence/getBarrelNum').then(v => {
      console.log(v, 'vv')
      if (v && v.obj) {
        let polygons = [];
        let id = '';
        if (v.obj && v.obj.length) {
          v.obj.map((item, index) => {
            let obj = {
              id: item.id,
              fillColor: item.fillColor,
              strokeColor: item.strokeColor,
              strokeWidth: item.strokeWidth,
              zIndex: item.zindex,
              name: item.name,
              points: item.points
            };
            id=obj.id;
            polygons.push(obj)
          })
        }
        this.setData({
          id: id,
          polygons: polygons
        })
      }
    }).catch(err => {
    })
  },
//每次创建标记点
    bindtapMap(e) {
  let tapPoint = e.detail;
  let markers = this.data.markers
  let newContent = markers.length
  let markerItem = {
    callout: {
      content: ++newContent,
      padding: 5,
      borderRadius: 2,
      // bgColor:'#ffffff96',
      bgColor: '#ffffff',
      display: 'ALWAYS',
      anchorY: -15,
      anchorX: 15,
      zIndex: 2
    },
    id: newContent,
    latitude: null,
    longitude: null,
    iconPath: '/images/maps/Marker1_Activated@3x.png',
    width: '34px',
    height: '34px',
    rotate: 0,
    alpha: 1,
    zIndex: 3
  }
  markerItem.latitude = tapPoint.latitude;
  markerItem.longitude = tapPoint.longitude;
  markers.push(markerItem)
  this.setData({
    markers
  })
},

//删除重复点击的标记点
    removeMarker(e) {
  console.log(e.markerId)
  let markers = this.data.markers;
  markers.splice(e.markerId - 1, 1)
  console.log(markers);
  //重置marker数组的id和content
  for (let j = 0; j < markers.length; j++) {
    markers[j].id = j + 1;
    markers[j].callout.content = j + 1;
  }
  this.setData({
    markers
  })
},

onLoad: function(options) {
  this.getPolygons();

  var that = this
  // 实例化API核心类
  tencentMap = new QQMapWX({
       key: 'HOSBZ-P6TCG-6V6QA-IAASE-M4ZJ6-4NBH6'
  });
  wx.getLocation({
       type: 'gcj02',
       success: function(res) {
            console.log(res);
            that.setData({
                 latitude: res.latitude,
                 longitude: res.longitude,
            });
       }
  })
},

  onReady: function() {
    //this.getLocation()
    this.getLngLat()
},

      //视野发生变化时触发
      regionchange(e) {
        if (e.type == 'end') {
             //this.getLngLat();
             var that = this;
             setTimeout(function(){
               that.getLngLat();
             },80)
        } else { //begin
        }
   },


//获取中间点的经纬度，并mark出来
getLngLat: function() {
    var that = this;
    // var curLongitude;
    // var curLatitude;
    this.mapCtx = wx.createMapContext("map");
    this.mapCtx.getCenterLocation({
         success: function(res) {
              that.setData({
                   markers: [{
                        id: 0,
                        iconPath: "../../images/maps/location.png",
                        longitude: res.longitude,
                        latitude: res.latitude,
                        zIndex:4,
                        width: 40,
                        height: 40
                   }],
                  //  longitude: res.longitude,
                  //  latitude: res.latitude
               })
              // this.data.curLongitude = res.longitude;
              // this.data.curLatitude = res.latitude;
                                 that.data.longitude=res.longitude;
                                 that.data.latitude= res.latitude;
              that.getPoiList(res.longitude, res.latitude)
         },

    })

},

getPoiList: function(longitude, latitude) {
  var that = this
  // 调用接口
  tencentMap.reverseGeocoder({
       location: {
            latitude: latitude,
            longitude: longitude,
       },
       get_poi: 1,
       poi_options: 'policy=2;radius=3000;page_size=20;page_index=1',
       success: function(res) {
            that.setData({
                 addressList: res.result.pois
            })
       },
       fail: function(res) {
            console.log(res);
       },
       complete: function(res) {
            console.log(res);
       }
  });
},

clickItem: function(e) {
  var index = e.currentTarget.dataset.index ? e.currentTarget.dataset.index:"0";
  var location = e.currentTarget.dataset.location;
  var siteData = this.data.siteData;
  var that = this
  that.data.latitude = location.lat
  that.data.longitude = location.lng
  console.log(location)
  that.setData({
    latitude: location.lat,
    longitude: location.lng,
  })
  this.tapHandle()
  if(this.data.flag==true){
 //*这里需要做一个判断，判断选定点是否在回收区域内。如果在区域内，则跳转页面到上一级并传参数（上一级页面的address直接改写）*
 let pages = getCurrentPages();
 let prevPage = pages[pages.length - 2];
 prevPage.setData({
     address: e.currentTarget.dataset.title,
     longitudeY : that.data.longitude,
     latitudeX : that.data.latitude,
     indexId : that.data.id

 })
 wx.navigateBack({
      delta: 1,
 })

  }


},

  /**
   * @description: 获取当前的地理位置
   * @return {获取当前位置的 longitude:经度  latitude:纬度 }
   **/
  getLocation: function () {
    let that = this
    wx.getLocation({
      type: 'wgs84', //wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success(res) {
        console.log(res)
        if (res.errMsg == "getLocation:ok") {
          that.getCurrentLocation(res.longitude, res.latitude) //选择当前位置的信息
          //this.moveToLocation(res.longitude, res.latitude)
          //that.openLocation(res.longitude, res.latitude)
          that.setData({
            longitudeY: res.longitude,
            latitudeX: res.latitude,
          })
        } else {
          common.errorMsg('定位请求失败！')
        }
      },
      fail: function (res) {
        common.errorMsg('请检查网络以及GPS定位是否开启')
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    })
  },






  /**
   * @description: 打开所在经纬度的位置的地图
   * @param {经度}  longitude
   * @param {纬度}  latitude
   * @return {获取传递的经纬度的地图 }
   **/
  openLocation: function (longitude, latitude) {
    wx.openLocation({
      longitude: longitude,
      latitude: latitude,
      name: '地址', //定位地址名称
      scale: 16, //缩放比例
      type: 'gcj02', //定位类型
    })
  },

  /**
   * @description: 打开地图选择位置,只有点击确定的时候触发
   * @param {经度}  longitude
   * @param {纬度}  latitude
   * @return {获取  adresss：地址； name:店名；  longitude:经度  latitude:纬度  }
   **/
  chooseLocation: function (longitude, latitude) {
    let that = this
    wx.chooseLocation({
      longitude: longitude,
      latitude: latitude,
      success: function (res) {
        console.log(res)
        if (res.errMsg == "chooseLocation:ok") {
          that.getPageData(res)
          wx.navigateBack()
        } else {
          common.errorMsg('选取位置失败')
          wx.navigateBack()
        }
      },
      fail: function (res) {
        common.errorMsg('选取位置失败')
        wx.navigateBack()
      }
    })
  },

  /**
   * @description: 获取前一个页面，并给前一个页面赋值
   * @param {传入请求成功的res}  res
   * @return {给前一个页面赋值  adresss：地址； name:店名；  longitude:经度  latitude:纬度  }
   **/
  getPageData: function (res) {
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    //给前一页赋值
    prevPage.setData({
      longitude: res.longitude, //经度
      latitude: res.latitude, //纬度
      address: res.address, //地址
      name: res.name, //店名
      //myLocation:res.location,
    })
  },

  /**
   * @description: 引入地图JSSDK,实现搜索地图周边，不传递location对象是根据当前位置
   * @param {搜索值}  keyword
   * @param {经度}  longitude
   * @param {纬度}  latitude
   * @return {获取  province：省； city:市；  district:区 等 }
   **/
  searchLocation: function (keyword, longitude, latitude) {
    let that = this
    var siteData = [];
    tencentMap.search({
      location: {
        longitude: longitude || that.data.longitude,
        latitude: latitude || that.data.latitude
      },
      keyword: keyword, //输入的搜索关键字
      success: function (res) {
        if (res.data.length > 0) {
          for (var i = 0; i < res.data.length; i++) {
            siteData.push({
              title: res.data[i].title,//名字
              id: res.data[i].id,//id
              da_info: res.data[i].da_info,//所属省市区
              address: res.data[i].address,//具体地址
              location: res.data[i].location,//坐标
              category: res.data[i].category,//类型
              tel: res.data[i].tel,//电话
              checked: false,//是否在选中
              scope: false,//是否在范围以内
            })
          };
        } else {
          siteData.push(data)
        }
        console.log(siteData[0].location);
        that.setData({
          addressList: res.data,
          // longitudeY : res.data.location.lng,
          // latitudeX : res.data.location.lat

     })
      },
      fail: function (res) {
        console.log(res);
      },
      /*       complete: function (res) {
              console.log(res);
            } */
    })
  },

  // 获取当前地理位置

  /**
   * @description: 使用经纬度解析出当前地理位置文字信息
   * @param {经度}  longitude
   * @param {纬度}  latitude
   * @return {获取  province：省； city:市；  district:区 等 }
   **/
  getCurrentLocation: function (longitude, latitude) {
    let that = this;
    tencentMap.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res)
        if (res.message == "query ok") {
          let result = res.result.ad_info
          let address = res.result.address

          that.setData({
            province: result.province,
            city: result.city,
            district: result.district,
            street: result.street,
            address: address,
          })
        } else {
          common.errorMsg('获取当前地点位置失败！')
        }
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },



  //搜索输入框
  searchInput: function (ele) {
    let that = this
    var e = ele.detail.value
    console.log(e)
    that.setData({
      searchValue: e
    })
  },

  //搜索框按钮--搜索
  searchBtn: function () {
    let that = this
    that.searchLocation(that.data.searchValue)
  },

})
